/*
 * 文 件    名:  MyCartService.java
 * 创建日期:  2012-10-10下午4:16:51
 * 版          权:  Epro Technologies Co., Ltd. Copyright 2011-2012,  All rights reserved
 * 作          者:  dc051
 */
package com.weipu.common.facade.content.api;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.weipu.common.facade.content.BaseService;
import com.weipu.common.facade.content.ContentURI;
import com.weipu.common.facade.content.colum.MyCartColumn;
import com.weipu.common.facade.content.impl.MyCartProviderImpl;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.util.Logger;

/** 
 * @Description 管理 service
 * @version [版本号, 2012-10-10]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 * 
 * @author dc051
 */
public class MyCartService extends BaseService
{
    
    MyCartProviderImpl myCartImpl = new MyCartProviderImpl();
    
    /**
     * 封装cursor 为java bean
     * @param cursor
     * @return [参数说明]
     * @return ArrayList<TemplateModel> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private ArrayList<OrderProductModel> getListByCursor(Cursor cursor)
    {
        if (isNullOrEmpty(cursor))
        {
            close(cursor);
            return null;
        }
        ArrayList<OrderProductModel> modelList = new ArrayList<OrderProductModel>(cursor.getCount());
        int[] idx =
            {cursor.getColumnIndex(MyCartColumn._ID), cursor.getColumnIndex(MyCartColumn.SKU),
                cursor.getColumnIndex(MyCartColumn.SHORTHEADLINE1), cursor.getColumnIndex(MyCartColumn.PRICE),
                cursor.getColumnIndex(MyCartColumn.QUANTITY), cursor.getColumnIndex(MyCartColumn.SMALLPICTUREURL),
                cursor.getColumnIndex(MyCartColumn.FREESHIPPING), cursor.getColumnIndex(MyCartColumn.LISTPRICE),/*,cursor.getColumnIndex(MyCartColumn.ISFAVORITE),*/cursor.getColumnIndex(MyCartColumn.MEDIUMPICTUREURL),};
        
        do
        {
            OrderProductModel model = new OrderProductModel();
            if (-1 != idx[0])
            {
                model.setId(cursor.getInt(idx[0]));
            }
            
            //body
            if (-1 != idx[1])
            {
                model.setSku(cursor.getInt(idx[1]));
            }
            
            //type
            if (-1 != idx[2])
            {
                model.setShortHeadLine1(cursor.getString(idx[2]));
            }
            //price
            if (-1 != idx[3])
            {
                model.setPrice(cursor.getFloat(idx[3]));
            }
            //count
            if (-1 != idx[4])
            {
                model.setQuantity(cursor.getInt(idx[4]));
            }
            if (-1 != idx[5])
            {
                model.setSmallPictureURL(cursor.getString(idx[5]));
            }
            if (-1 != idx[6])
            {
                model.setFreeShipping(cursor.getInt(idx[6]));
            }
            
            if (-1 != idx[7])
            {
                model.setlistprice(cursor.getFloat(idx[7]));
            }
           /* if (-1 != idx[8])
            {
                model.setIsFavorite(cursor.getString(idx[8]));
            }*/
            if (-1 != idx[8])
            {
                model.setMediumPictureURL(cursor.getString(idx[8]));
            }
            modelList.add(model);
        } while (cursor.moveToNext());
        close(cursor);
        return modelList;
    }
    
    /**
     * 获取指定类型的模板列表
     * @param type 日报/周报
     * {@link ContentConstant.Common#CONTENT_TYPE_DAILY}
     * {@link ContentConstant.Common#CONTENT_TYPE_WEEKLY}
     * @return [参数说明]
     * @return ArrayList<TemplateModel> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public ArrayList<OrderProductModel> getListByType(Context context, String type)
    {
        if (!check(context, type))
        {
            return null;
        }
        return getListByCursor(context.getContentResolver().query(ContentURI.ContentMyCart.CONTENT_URI_ALL,
            null,
            null,
            null,
            null));
    }
    
    public ArrayList<OrderProductModel> getBySelection(Context context, String selection, String... args)
    {
        if (!check(context))
        {
            return null;
        }
        return getListByCursor(context.getContentResolver().query(ContentURI.ContentMyCart.CONTENT_URI_ALL,
            null,
            selection,
            args,
            null));
        
    }
    
    /**
     * 根据id查询指定模板
     * @param context
     * @param id 模板id
     * @return [参数说明]
     * @return ArrayList<TemplateModel> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public OrderProductModel getById(Context context, long id)
    {
        if (!check(context))
        {
            return null;
        }
        if (id < 0)
        {
            return null;
        }
        ArrayList<OrderProductModel> modelList =
            getListByCursor(context.getContentResolver()
                .query(ContentUris.withAppendedId(ContentURI.ContentMyCart.CONTENT_URI_BY_ID, id),
                    null,
                    null,
                    null,
                    null));
        if (null == modelList || modelList.isEmpty())
        {
            return null;
        }
        return modelList.get(0);
    }
    
    /**
     * 根据sku查询指定模板
     * @param context
     * @param sku 商品sku
     * @return [参数说明]
     * @return ArrayList<TemplateModel> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public OrderProductModel getBySku(Context context, int sku)
    {
        if (!check(context))
        {
            return null;
        }
        if (sku < 0)
        {
            return null;
        }
        ArrayList<OrderProductModel> modelList =
            getListByCursor(context.getContentResolver().query(ContentURI.ContentMyCart.CONTENT_URI_ALL,
                null,
                "sku=?",
                new String[] {String.valueOf(sku)},
                null));
        if (null == modelList || modelList.isEmpty())
        {
            return null;
        }
        return modelList.get(0);
    }
    
    /**
     * 自定义条件查询并返回游标
     * @param context
     * @param projection
     * @param selection
     * @param args
     * @return [参数说明]
     * @return Cursor [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public Cursor queryBySelection(Context context, String[] projection, String selection, String[] args,
        String sortOrder)
    {
        return context.getContentResolver().query(ContentURI.ContentMyCart.CONTENT_URI_ALL,
            projection,
            selection,
            args,
            sortOrder);
    }
    
    /**
                  * 保存
     * @param context
     * @param model
     * @return [参数说明]
     * @return long [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public long save(Context context, OrderProductModel model)
    {
        if (!check(context, model))
        {
            return -1;
        }
        ContentValues map = model.template2map();
        try
        {
            Uri uri = myCartImpl.insert(ContentURI.ContentMyCart.CONTENT_URI_ALL, map);
            //           Uri uri= context.getContentResolver()
            //                    .insert(ContentURI.ContentMyCart.CONTENT_URI_ALL, map);
            Logger.d("uri:" + uri);
        }
        catch (Exception e)
        {
            return -1;
        }
        
        Long result = map.getAsLong(MyCartColumn._ID);
        
        long returnId = (null != result ? result : -1);
        
        return returnId;
        //        return 1;
    }
    
    /**
     * 保存
     * @param context
     * @param model
     * @return [参数说明]
     * @return long [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public long update(Context context, OrderProductModel model)
    {
        if (!check(context, model))
        {
            return -1;
        }
        
        //原来的id
        int currentModelID = model.getId();
        
        if (currentModelID < 0)
        {
            return -1;
        }
        
        model.setId(-1);
        
        int updateRow = -1;
        try
        {
            //根据SKU查询商品对象
            ArrayList<OrderProductModel> cartList =
                getBySelection(context, MyCartColumn.SKU + "=?", new String[] {String.valueOf(model.getSku())});
            
            OrderProductModel curModel = null;
            
            if (null != cartList && cartList.size() > 0)
            {
                curModel = cartList.get(0);
            }
            
            //            数据存在
            if (null != curModel)
            {
                //数量超过999
                //                if (model.getQuantity() > 999)
                //                {
                //                    model.setQuantity(999);
                //                }
                //                else 
                if (model.getQuantity() <= 0)
                {
                    model.setQuantity(1);
                }
                //更新数据库，指定id,
                updateRow =
                    myCartImpl.update(ContentURI.ContentMyCart.CONTENT_URI_ALL, model.template2map(), MyCartColumn._ID
                        + "=" + currentModelID, null);
            }
            //UI验证
            //            //现有数据无效，直接返回0
            //            else
            //            {
            //                updateRow = 0;
            //            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        //还原原始ID(防止UI会继续使用 到 该对象 )
        model.setId(currentModelID);
        
        return updateRow;
    }
    
    /**
     * 根据id删除指定模板
     * @param context
     * @param id 模板id
     * @return [参数说明]
     * @return ArrayList<TemplateModel> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public int deleteById(Context context, long id)
    {
        if (!check(context))
        {
            return -1;
        }
        
        if (id < 0)
        {
            return -1;
        }
        
        int deleteRow = -1;
        
        try
        {
            deleteRow =
                myCartImpl.delete(ContentURI.ContentMyCart.CONTENT_URI_ALL,
                    MyCartColumn._ID + "=?",
                    new String[] {String.valueOf(id)});
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return deleteRow;
    }
    
    /**
     * 自定义条件删除
     * @param context
     * @param selection 删除条件
     * @param args 条件参数
     * @return [参数说明]
     * @return int [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public int deleteTemplateBySelection(Context context, String selection, String[] args)
    {
        if (!check(context))
        {
            return -1;
        }
        
        int deleteRow = -1;
        try
        {
            deleteRow = context.getContentResolver().delete(ContentURI.ContentMyCart.CONTENT_URI_ALL, selection, args);
        }
        catch (Exception e)
        {
            //ignore
        }
        return deleteRow;
    }
    
    public ArrayList<OrderProductModel> selectMenusList(Context context, String sortOrder)
    {
        Cursor cursor = this.queryBySelection(context, MyCartColumn.RESULT, null, null, sortOrder);
        
        ArrayList<OrderProductModel> menuList = new ArrayList<OrderProductModel>();
        if (cursor == null)
        {
        }
        else
        {
            cursor.moveToFirst();
            if (cursor.getCount() > 0)
            {
                do
                {
                    OrderProductModel temp = new OrderProductModel();
                    temp.setId(cursor.getInt(0));
                    temp.setSku(cursor.getInt(1));
                    temp.setShortHeadLine1(cursor.getString(2));
                    temp.setPrice(cursor.getFloat(3));
                    temp.setQuantity(cursor.getInt(4));
                    temp.setSmallPictureURL(cursor.getString(5));
                    temp.setFreeShipping(cursor.getInt(6));
                    temp.setlistprice(cursor.getFloat(7));
                    if(-1!=cursor.getColumnIndex(MyCartColumn.MEDIUMPICTUREURL)){
                    	temp.setMediumPictureURL(cursor.getString(8));
                    }
//                    temp.setMediumPictureURL(cursor.getString(8));
//                    temp.setIsFavorite(cursor.getString(8));
//                    Log.i("TAGA",  temp.getMediumPictureURL()+" VVV "+temp.getSmallPictureURL());
//                    //cursor.getColumnIndex("isFavorite");
                    menuList.add(temp);
                    //后移
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        
        return menuList;
    }
    
    public int getQuantityBySku(Context context, long sku)
    {
        List<OrderProductModel> localeCartList = selectMenusList(context, "_id desc");
        
        for (int i = 0; i < localeCartList.size(); i++)
        {
            if (sku == (localeCartList.get(i)).getSku())
            {
                return localeCartList.get(i).getQuantity();
            }
        }
        return 1000;
    }
    
    /**  
     * <功能详细描述>
     * @param context
     * @param sku
     * @return
     * @see [类、类#方法、类#成员]
     */
    public int getCartTotal(Context context)
    {
        int total = 0;
        List<OrderProductModel> localeCartList = selectMenusList(context, "_id desc");
        if (!localeCartList.isEmpty())
        {
        	//by huangfei 累计按产品种类计算 不按产品数量
        	total=localeCartList.size();
//            for (int i = 0; i < localeCartList.size(); i++)
//            {
//                total += localeCartList.get(i).getQuantity();
//            }
        }
        return total;
    }
    
}
